"""PaperPal主应用程序"""

import streamlit as st
from config import Config
from agent.paperpal_agent import PaperPalAgent, PaperPalChatbot, PaperComparator
from prompts.comparison_prompts import PAPER_COMPARISON_PROMPT
from agent.utils import ValidationUtils
from streamlit_mermaid import st_mermaid
from streamlit_ace import st_ace
import time

# 页面配置
st.set_page_config(
    page_title=Config.PAGE_TITLE,
    page_icon=Config.PAGE_ICON,
    layout="wide",
    initial_sidebar_state="expanded"
)

def render_mermaid_with_html(mindmap_code, chart_id):
    """使用HTML iframe方式渲染mermaid图表，支持下载功能"""
    
    # 创建HTML模板，包含下载功能
    html_template = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    </head>
    <body>
        <div id="mermaid-container">
            <div class="mermaid" id="{chart_id}">
{mindmap_code}
            </div>
        </div>
        
        <div style="text-align: center; margin-top: 20px;">
            <button onclick="downloadChart()" style="
                background-color: #4CAF50;
                border: none;
                color: white;
                padding: 15px 32px;
                text-align: center;
                text-decoration: none;
                display: inline-block;
                font-size: 16px;
                margin: 4px 2px;
                cursor: pointer;
                border-radius: 4px;
            ">📥 下载为PNG</button>
        </div>
        
        <script>
            // 立即配置并初始化Mermaid
            mermaid.initialize({{
                startOnLoad: true,
                theme: 'default',
                mindmap: {{
                    padding: 20
                }},
                securityLevel: 'loose'
            }});
            
            // 下载功能
            function downloadChart() {{
                const element = document.querySelector('.mermaid svg');
                if (!element) {{
                    alert('思维导图尚未加载完成，请稍后再试');
                    return;
                }}
                
                html2canvas(document.querySelector('#mermaid-container'), {{
                    backgroundColor: '#ffffff',
                    scale: 2,
                    useCORS: true,
                    allowTaint: true
                }}).then(canvas => {{
                    const link = document.createElement('a');
                    link.download = 'mindmap_{chart_id}.png';
                    link.href = canvas.toDataURL();
                    link.click();
                }}).catch(error => {{
                    console.error('下载失败:', error);
                    alert('下载失败，请检查浏览器设置');
                }});
            }}
            
            // 添加多重初始化保障
            document.addEventListener('DOMContentLoaded', function() {{
                setTimeout(function() {{
                    if (typeof mermaid !== 'undefined') {{
                        mermaid.init();
                    }}
                }}, 500);
            }});
            
            // 页面加载完成后再次尝试初始化
            window.addEventListener('load', function() {{
                setTimeout(function() {{
                    if (typeof mermaid !== 'undefined') {{
                        mermaid.init();
                    }}
                }}, 100);
            }});
        </script>
        <style>
            body {{ 
                font-family: Arial, sans-serif; 
                margin: 20px;
                background: white;
            }}
            #mermaid-container {{
                background: white;
                padding: 20px;
                border-radius: 8px;
                text-align: center;
                min-height: 400px;
            }}
            .mermaid {{
                width: 100%;
                height: auto;
            }}
        </style>
    </body>
    </html>
    """
    
    # 使用streamlit的HTML组件
    st.components.v1.html(html_template, height=700, scrolling=True)

def mermaid_mindmap_to_markdown(mermaid_code: str) -> str:
    lines = mermaid_code.strip().splitlines()
    markdown_lines = []

    for line in lines:
        if not line.strip() or line.strip().startswith("mindmap"):
            continue
        # 统计前导空格来判断层级（两个空格一个层级）
        indent_level = (len(line) - len(line.lstrip(" "))) // 2
        content = line.strip()
        if content.startswith("root(") and content.endswith(")"):
            content = content[5:-1]  # 去除 root(...)
        elif content.endswith(")") and "(" in content:
            content = content[content.find("(")+1:-1]  # 去除 name(...)
        markdown_lines.append("  " * indent_level + f"- {content}")

    return "\n".join(markdown_lines)

def init_session_state():
    """初始化会话状态"""
    if "agent" not in st.session_state:
        st.session_state.agent = None
    if "processing_results" not in st.session_state:
        st.session_state.processing_results = None
    if "chatbot" not in st.session_state:
        st.session_state.chatbot = None
    if "api_key_validated" not in st.session_state:
        st.session_state.api_key_validated = False
    
    # 对比相关的状态
    if "comparison_paper1" not in st.session_state:
        st.session_state.comparison_paper1 = None
    if "comparison_paper2" not in st.session_state:
        st.session_state.comparison_paper2 = None
    if "comparison_results" not in st.session_state:
        st.session_state.comparison_results = None
    if "comparison_mode" not in st.session_state:
        st.session_state.comparison_mode = False

def render_sidebar():
    """渲染侧边栏"""
    with st.sidebar:
        st.title("🔧 配置")
        
        # API Key配置
        st.subheader("API设置")
        api_key = st.text_input(
            "ZhipuAI API Key",
            type="password",
            help="请输入您的ZhipuAI API Key",
            value=st.session_state.get("api_key", "")
        )
        
        if st.button("验证API Key"):
            # 先检查格式
            if not ValidationUtils.validate_api_key(api_key):
                st.error("❌ API Key格式不正确 (长度至少30字符)")
            else:
                # 添加加载指示器
                with st.spinner("正在验证API Key，可能需要几秒钟..."):
                    # 实际测试API Key有效性
                    is_valid, message = ValidationUtils.validate_api_key_with_request(api_key)
                    if is_valid:
                        st.session_state.api_key_validated = True
                        st.session_state.api_key = api_key  # 存储验证通过的API Key
                        st.session_state.agent = PaperPalAgent(api_key)
                        st.success(f"✅ {message}")
                    else:
                        st.error(f"❌ API Key验证失败: {message}")
                        # 添加调试信息
                        st.info("调试提示：")
                        st.markdown("""
                        - 请确保API Key正确且未过期
                        - 检查网络连接是否正常
                        - 尝试在[智谱AI开放平台](https://open.bigmodel.cn/)测试API Key
                        - 如果问题持续，请检查防火墙设置
                        """)
        st.divider()
        
        # 使用说明
        st.subheader("📖 使用说明")
        st.markdown("""
        1. **配置 API**：在侧边栏输入并验证 ZhipuAI API Key，确保后续功能可用  
        2. **上传论文**：支持单篇分析或对比分析两种模式  
            - 默认模式下，上传 **一篇 PDF 论文**  
            - 勾选“启用论文对比功能”后，可上传 **两篇 PDF 论文**  
        3. **开始分析**：点击“开始分析”或“开始对比分析”按钮，等待 Agent 处理论文内容  
        4. **查看结果**：获取每篇论文的摘要、思维导图、公式解释、专家解读以及论文溯源结果  
        5. **互动问答**：分析完成后，可基于论文或论文对比结果与 Agent 进行智能问答  
        6. **重复使用**：可随时切换分析模式并上传其他论文进行新一轮分析
        """)
        
        st.divider()
        
        # 系统信息
        st.subheader("ℹ️ 系统信息")
        st.info(f"""
        **模型**: {Config.MODEL_NAME}\n
        **最大上下文**: {Config.MAX_TOKENS:,} tokens\n
        **支持格式**: PDF\n
        **最大文件**: 10MB
        """)

def render_main_content():
    """渲染主要内容"""
    
    # 标题
    st.title("📚 PaperPal - 论文速读Agent")
    st.markdown("*让AI帮您快速理解学术论文*")
    
    # 检查API Key
    if not st.session_state.api_key_validated:
        st.warning("⚠️ 请先在侧边栏配置并验证API Key")
        return
    
    # 文件上传区域
    st.subheader("📄 上传论文")
    comparison_mode = st.checkbox("启用论文对比功能")
    
    if comparison_mode:
        st.session_state.comparison_mode = True
        st.info("论文对比模式已启用，请上传两篇论文进行对比分析")
        st.subheader("📊 论文对比功能")
        
        col1, col2 = st.columns(2)
        
        with col1:
            st.subheader("📄 上传论文A")
            uploaded_file1 = st.file_uploader(
                "选择第一篇PDF文件",
                type=['pdf'],
                key="comparison_file1",
                help="支持PDF格式的学术论文，最大10MB"
            )
            if uploaded_file1:
                st.session_state.comparison_paper1 = uploaded_file1
        
        with col2:
            st.subheader("📄 上传论文B")
            uploaded_file2 = st.file_uploader(
                "选择第二篇PDF文件",
                type=['pdf'],
                key="comparison_file2",
                help="支持PDF格式的学术论文，最大10MB"
            )
            if uploaded_file2:
                st.session_state.comparison_paper2 = uploaded_file2
        
        # 当两篇论文都已上传时显示对比按钮
        if st.session_state.comparison_paper1 and st.session_state.comparison_paper2:
            if st.button("🔍 开始对比分析", type="primary"):
                with st.spinner("正在对比两篇论文，请稍候..."):
                    # 处理两篇论文
                    paper1 = st.session_state.agent.process_pdf(st.session_state.comparison_paper1)
                    paper2 = st.session_state.agent.process_pdf(st.session_state.comparison_paper2)
                    
                    # 进行对比
                    comparator = PaperComparator(st.session_state.agent.api_key)
                    comparison = comparator.compare(
                        paper1.get("summary", ""),
                        paper2.get("summary", "")
                    )
                    
                    st.session_state.comparison_results = {
                        "comparison": comparison,
                        "paper1_title": st.session_state.comparison_paper1.name,
                        "paper2_title": st.session_state.comparison_paper2.name,
                        "paper1_results": paper1,
                        "paper2_results": paper2
                    }

                    # 创建聊天机器人（基于两篇论文的摘要）
                    combined_summary = f"论文A ({st.session_state.comparison_paper1.name}):\n{paper1.get('summary', '')}\n\n论文B ({st.session_state.comparison_paper2.name}):\n{paper2.get('summary', '')}"
                    st.session_state.chatbot = PaperPalChatbot(
                        st.session_state.agent.api_key,
                        combined_summary
                    )

                    st.success("🎉 对比分析完成！")
                    st.rerun()
    else:
        st.session_state.comparison_mode = False
        uploaded_file = st.file_uploader(
            "选择PDF文件",
            type=['pdf'],
            help="支持PDF格式的学术论文，最大10MB"
        )
        
        if uploaded_file is not None:
            # 显示文件信息
            col1, col2, col3 = st.columns(3)
            with col1:
                st.metric("文件名", uploaded_file.name)
            with col2:
                st.metric("文件大小", f"{uploaded_file.size / 1024:.1f} KB")
            with col3:
                st.metric("文件类型", "PDF")
            
            # 处理按钮
            if st.button("🚀 开始分析", type="primary"):
                with st.spinner("正在分析论文，请稍候..."):
                    # 处理PDF
                    results = st.session_state.agent.process_pdf(uploaded_file)
                    
                    if "error" in results:
                        st.error(f"处理失败: {results['error']}")
                    else:
                        st.session_state.processing_results = results
                        # 创建聊天机器人
                        paper_summary = results.get("summary", "")
                        st.session_state.chatbot = PaperPalChatbot(
                            st.session_state.agent.api_key,
                            # paper_summary
                            results.get("raw_text", "")
                        )
                        st.rerun()
    
def render_results():
    """渲染分析结果"""
    if st.session_state.processing_results is None:
        return
    
    results = st.session_state.processing_results
    
    # 结果展示区域
    st.divider()
    st.subheader("📊 分析结果")
    
    # 创建标签页
    tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8 = st.tabs([
        "📋 论文摘要", 
        "🗺️ 思维导图", 
        "🧮 公式解释", 
        "💬 智能问答",
        "📚 论文推荐",
        "📝 专家视角",
        "🔍 论文溯源",
        "📈 处理报告"
    ])
    
    with tab1:
        st.markdown("### 📝 论文摘要")
        summary = results.get("summary", "摘要生成失败")
        st.markdown(summary)
        
        # 下载摘要
        st.download_button(
            label="📥 下载摘要",
            data=summary,
            file_name=f"summary_{results.get('file_name', 'paper')}.md",
            mime="text/markdown"
        )
    
    with tab2:
        st.markdown("### 🗺️ 思维导图")
        mindmap_code = results.get("mindmap", "")
        
        if mindmap_code and "mindmap" in mindmap_code:
            # 提供多种显示选项
            display_option = st.radio(
                "选择显示方式：",
                ["内嵌显示", "文本结构", "代码查看", "编辑模式"],
                horizontal=True,
                key="mindmap_display_option"
            )
            
            if display_option == "内嵌显示":
                # 添加一个刷新按钮和说明文字
                refresh_col, info_col = st.columns([2, 6])
                with refresh_col:
                    if st.button("🔄 刷新显示", key="refresh_mindmap"):
                        st.rerun()
                with info_col:
                    st.caption("💡 首次加载可能无法显示，请点击刷新按钮")
                try:
                    timestamp = int(time.time() * 1000)
                    render_mermaid_with_html(mindmap_code, f"mindmap_{timestamp}")
                except Exception as e:
                    st.error(f"内嵌显示失败: {str(e)}")
                    st.code(mindmap_code, language="mermaid")
                    
            elif display_option == "文本结构":
                st.markdown("#### 📋 文本结构")
                markdown_outline = mermaid_mindmap_to_markdown(mindmap_code)
                st.markdown(markdown_outline)
                st.download_button(
                    label="📥 下载 Markdown 文件",
                    data=markdown_outline,
                    file_name="mindmap_outline.md",
                    mime="text/markdown"
                )
            
            elif display_option == "编辑模式":
                st.markdown("#### ✏️ 思维导图编辑器")

                edited_code = st_ace(
                    value=mindmap_code,
                    language="mermaid",  # 或尝试 "mermaid"、"text"
                    theme="monokai",
                    keybinding="vscode",
                    font_size=14,
                    tab_size=2,
                    height=400,
                    key="mindmap_editor_ace"
                )

                if st.button("🔄 渲染编辑后的思维导图"):
                    try:
                        timestamp = int(time.time() * 1000)
                        render_mermaid_with_html(edited_code, f"mindmap_edit_{timestamp}")
                    except Exception as e:
                        st.error(f"渲染失败: {str(e)}")
                        st.code(edited_code, language="mermaid")

                st.download_button(
                    label="📥 下载编辑后的Mermaid代码",
                    data=edited_code,
                    file_name="edited_mindmap.mmd",
                    mime="text/plain"
                )
                
            else:  # 代码查看
                st.markdown(f"可复制以下代码到任何支持Mermaid的工具中")
                st.code(mindmap_code, language="mermaid")
                
        else:
            st.warning("思维导图生成失败或格式不正确")
            if mindmap_code:
                st.code(mindmap_code, language="mermaid")

    with tab3:
        st.markdown("### 🧮 公式解释")
        formula_explanations = results.get("formula_explanation", None)

        if not formula_explanations:
            st.warning("未能提取到公式解释")
        else:
            if isinstance(formula_explanations, str):
                st.markdown(formula_explanations)  # 兼容旧格式
            else:
                for i, item in enumerate(formula_explanations):
                    with st.container():
                        st.markdown(f"**公式 {i+1}:**")
                        try:
                            st.latex(item['latex'])
                        except Exception:
                            st.code(item['latex'], language="latex")
                        st.markdown(f"📝 {item['context']}")
                        st.divider()

    with tab4:
        st.markdown("### 💬 智能问答")
        
        if st.session_state.chatbot is not None:
            # 问答界面
            question = st.text_input("请输入您想了解的问题：", placeholder="例如：这篇论文的主要创新点是什么？")
            
            if st.button("🤔 提问") and question:
                with st.spinner("正在思考..."):
                    answer = st.session_state.chatbot.ask_question(question)
                    st.markdown(f"**问题**: {question}")
                    st.markdown(f"**回答**: {answer}")
            
            # 显示历史对话
            chat_history = st.session_state.chatbot.get_chat_history()
            if chat_history:
                st.markdown("#### 📝 对话历史")
                for i, chat in enumerate(reversed(chat_history[-5:])):  # 显示最近5次对话
                    with st.expander(f"Q{len(chat_history)-i}: {chat['question'][:50]}..."):
                        st.markdown(f"**问题**: {chat['question']}")
                        st.markdown(f"**回答**: {chat['answer']}")
        else:
            st.warning("请先完成论文分析后再进行问答")

    with tab5:  # 论文推荐标签页
        st.markdown("### 📚 相关论文推荐")

        recommendations = results.get("recommendations", "推荐生成失败")

        if isinstance(recommendations, list):
            for i, rec in enumerate(recommendations, 1):
                st.markdown(f"**{i}. {rec['title']}** - {rec['author']}, {rec['year']}")
                st.markdown(f"- 领域：{rec['field']}")
                st.markdown(f"- 摘要：{rec['abstract']}")
                st.markdown("---")
        else:
            st.markdown(recommendations)

    with tab6:
        st.markdown("### 📝 专家视角")
        expert_feedback = results.get("expert_feedback", "专家视角生成失败")
        st.markdown(expert_feedback)
    
    with tab7:
        st.markdown("### 🔍 论文溯源分析")

        if results.get("trace_complete", False):
            citation_analysis = results.get("citation_analysis", "溯源分析失败")
            citation_graph = results.get("citation_graph", "")

            st.markdown("#### 📊 引用影响力分析")
            st.markdown(citation_analysis)

            if citation_graph:
                try:
                    timestamp = int(time.time() * 1000)
                    render_mermaid_with_html(citation_graph, f"citation_{timestamp}")
                except Exception as e:
                    st.error(f"内嵌显示失败: {str(e)}")
                    st.code(citation_graph, language="mermaid")
            else:
                st.info("未生成引用关系图")
        else:
            st.info("溯源分析结果暂未生成")
    with tab8:
        st.markdown("### 📈 处理报告")
        
        # 基本信息
        paper_info = st.session_state.agent.get_paper_info(results)
        
        col1, col2 = st.columns(2)
        with col1:
            st.markdown("#### 📄 论文信息")
            for key, value in paper_info.items():
                st.metric(key, value)
        
        with col2:
            st.markdown("#### ⚙️ 处理状态")
            status = st.session_state.agent.get_processing_status(results)
            for component, completed in status.items():
                status_icon = "✅" if completed else "❌"
                st.markdown(f"{status_icon} **{component}**: {'完成' if completed else '失败'}")

def render_comparison_results():
    """渲染对比分析结果"""
    if not st.session_state.comparison_results:
        return
    
    results = st.session_state.comparison_results
    paper1_results = results.get("paper1_results", {})
    paper2_results = results.get("paper2_results", {})
    
    st.divider()
    st.subheader("📊 分析结果")    

    # 创建标签页
    tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8, tab9 = st.tabs([
        "↔️ 对比报告", 
        "📊 差异总结",
        "🗺️ 思维导图", 
        "🧮 公式解释", 
        "💬 智能问答",
        "📚 论文推荐",
        "📝 专家视角",
        "🔍 论文溯源",
        "📈 处理报告"
    ])

    with tab1:
        comparison_text = results["comparison"]
        if "## 💡 总结与差异分析" in comparison_text:
            summary_start = comparison_text.index("## 💡 总结与差异分析")
            main_report = comparison_text[:summary_start]  # 只显示总结之前的部分
            st.markdown(main_report)
        else:
            st.markdown(comparison_text)
        
        # 下载对比报告
        st.download_button(
            label="📥 下载对比报告",
            data=results["comparison"],
            file_name=f"comparison_{results['paper1_title']}_vs_{results['paper2_title']}.md",
            mime="text/markdown"
        )

    with tab2:
        # 提取差异总结部分
        comparison_text = results["comparison"]
        if "## 💡 总结与差异分析" in comparison_text:
            summary_start = comparison_text.index("## 💡 总结与差异分析")
            summary = comparison_text[summary_start:]
            st.markdown(summary)
        else:
            st.warning("无法提取差异总结部分")
            st.markdown(comparison_text)

    with tab3:
        st.markdown(f"#### 🗺️ {results['paper1_title']}")
        mindmap1 = paper1_results.get("mindmap", "")

        if mindmap1 and "mindmap" in mindmap1:
            # 提供多种显示选项
            display_option = st.radio(
                "选择显示方式：",
                ["内嵌显示", "文本结构", "代码查看", "编辑模式"],
                horizontal=True,
                key="mindmap_display_paper1"
            )

            if display_option == "内嵌显示":
                refresh_col, info_col = st.columns([2, 6])
                with refresh_col:
                    if st.button("🔄 刷新显示", key="refresh_mindmap1"):
                        st.rerun()
                with info_col:
                    st.caption("💡 首次加载可能无法显示，请点击刷新按钮")
                try:
                    timestamp = int(time.time() * 1000)
                    render_mermaid_with_html(mindmap1, f"mindmap_{timestamp}")
                except Exception as e:
                    st.error(f"内嵌显示失败: {str(e)}")
                    st.code(mindmap1, language="mermaid")
                    
            elif display_option == "文本结构":
                st.markdown("**📋 文本结构**")
                markdown_outline = mermaid_mindmap_to_markdown(mindmap1)
                st.markdown(markdown_outline)
                st.download_button(
                    label="📥 下载 Markdown 文件",
                    data=markdown_outline,
                    file_name="mindmap1_outline.md",
                    mime="text/markdown",
                    key="download_markdown_paper1"
                )

            elif display_option == "编辑模式":
                st.markdown("#### ✏️ 思维导图编辑器")

                edited_code = st_ace(
                    value=mindmap1,
                    language="mermaid",
                    theme="monokai",
                    keybinding="vscode",
                    font_size=14,
                    tab_size=2,
                    height=400,
                    key="mindmap1_editor_ace"
                )

                if st.button("🔄 渲染编辑后的思维导图（论文1）", key="render_edited_mindmap1"):
                    try:
                        timestamp = int(time.time() * 1000)
                        render_mermaid_with_html(edited_code, f"mindmap_edit_{timestamp}")
                    except Exception as e:
                        st.error(f"渲染失败: {str(e)}")
                        st.code(edited_code, language="mermaid")

                st.download_button(
                    label="📥 下载编辑后的Mermaid代码",
                    data=edited_code,
                    file_name="edited_mindmap1.mmd",
                    mime="text/plain",
                    key="download_edited_mermaid1"
                )
            else:
                st.markdown(f"可复制以下代码到任何支持Mermaid的工具中")
                st.code(mindmap1, language="mermaid")
        else:
            st.warning("思维导图生成失败或格式不正确")
            if mindmap1:
                st.code(mindmap1, language="mermaid")
        
        st.markdown(f"#### 🗺️ {results['paper2_title']}")
        mindmap2 = paper2_results.get("mindmap", "")

        if mindmap2 and "mindmap" in mindmap2:
            # 提供多种显示选项
            display_option2 = st.radio(
                "选择显示方式：",
                ["内嵌显示", "文本结构", "代码查看", "编辑模式"],
                horizontal=True,
                key="mindmap_display_paper2"
            )

            if display_option2 == "内嵌显示":
                refresh_col, info_col = st.columns([2, 6])
                with refresh_col:
                    if st.button("🔄 刷新显示", key="refresh_mindmap2"):
                        st.rerun()
                with info_col:
                    st.caption("💡 首次加载可能无法显示，请点击刷新按钮")
                try:
                    timestamp = int(time.time() * 1000)
                    render_mermaid_with_html(mindmap2, f"mindmap_{timestamp}")
                except Exception as e:
                    st.error(f"内嵌显示失败: {str(e)}")
                    st.code(mindmap2, language="mermaid")
                    
            elif display_option2 == "文本结构":
                st.markdown("**📋 文本结构**")
                markdown_outline = mermaid_mindmap_to_markdown(mindmap2)
                st.markdown(markdown_outline)
                st.download_button(
                    label="📥 下载 Markdown 文件",
                    data=markdown_outline,
                    file_name="mindmap2_outline.md",
                    mime="text/markdown",
                    key="download_markdown_paper2"
                )
            elif display_option2 == "编辑模式":
                st.markdown("#### ✏️ 思维导图编辑器")

                edited_code2 = st_ace(
                    value=mindmap2,
                    language="mermaid",
                    theme="monokai",
                    keybinding="vscode",
                    font_size=14,
                    tab_size=2,
                    height=400,
                    key="mindmap2_editor_ace"
                )

                if st.button("🔄 渲染编辑后的思维导图（论文2）", key="render_edited_mindmap2"):
                    try:
                        timestamp = int(time.time() * 1000)
                        render_mermaid_with_html(edited_code2, f"mindmap_edit_{timestamp}")
                    except Exception as e:
                        st.error(f"渲染失败: {str(e)}")
                        st.code(edited_code2, language="mermaid")

                st.download_button(
                    label="📥 下载编辑后的Mermaid代码",
                    data=edited_code2,
                    file_name="edited_mindmap2.mmd",
                    mime="text/plain",
                    key="download_edited_mermaid2"
                )
            else:
                st.markdown(f"可复制以下代码到任何支持Mermaid的工具中")
                st.code(mindmap2, language="mermaid")
        else:
            st.warning("思维导图生成失败或格式不正确")
            if mindmap2:
                st.code(mindmap2, language="mermaid")

    with tab4:
        st.markdown("### 🧮 公式解释")

        st.markdown(f"#### 🧮 {results['paper1_title']}")
        formula1 = paper1_results.get("formula_explanation", None)
        if not formula1:
            st.warning("未能提取到公式解释")
        else:
            if isinstance(formula1, str):
                st.markdown(formula1)  # 兼容旧格式
            else:
                for i, item in enumerate(formula1):
                    with st.container():
                        st.markdown(f"**公式 {i+1}:**")
                        try:
                            st.latex(item['latex'])
                        except Exception:
                            st.code(item['latex'], language="latex")
                        st.markdown(f"📝 {item['context']}")
                        st.divider()

        st.markdown(f"#### 🧮 {results['paper2_title']}")
        formula2 = paper2_results.get("formula_explanation", None)
        if not formula2:
            st.warning("未能提取到公式解释")
        else:
            if isinstance(formula2, str):
                st.markdown(formula2)  # 兼容旧格式
            else:
                for i, item in enumerate(formula2):
                    with st.container():
                        st.markdown(f"**公式 {i+1}:**")
                        try:
                            st.latex(item['latex'])
                        except Exception:
                            st.code(item['latex'], language="latex")
                        st.markdown(f"📝 {item['context']}")
                        st.divider()

    with tab5:
        st.markdown("### 💬 智能问答")
        
        if st.session_state.chatbot is not None:
            # 问答界面
            question = st.text_input("请输入您想了解的问题：", placeholder="例如：这两篇论文的主要差异是什么？", key="comparison_question")
            
            if st.button("🤔 提问", key="comparison_ask") and question:
                with st.spinner("正在思考..."):
                    answer = st.session_state.chatbot.ask_question(question)
                    st.markdown(f"**问题**: {question}")
                    st.markdown(f"**回答**: {answer}")
            
            # 显示历史对话
            chat_history = st.session_state.chatbot.get_chat_history()
            if chat_history:
                st.markdown("#### 📝 对话历史")
                for i, chat in enumerate(reversed(chat_history[-5:])):
                    with st.expander(f"Q{len(chat_history)-i}: {chat['question'][:50]}..."):
                        st.markdown(f"**问题**: {chat['question']}")
                        st.markdown(f"**回答**: {chat['answer']}")
        else:
            st.warning("请先完成论文分析后再进行问答")

    with tab6:
        st.markdown("### 📚 相关论文推荐")
        # 基于两篇论文生成综合推荐
        if st.button("🔍 生成综合推荐", key="generate_combined_recommendations"):
            with st.spinner("正在生成基于两篇论文的综合推荐..."):
                try:
                    # 获取两篇论文的摘要
                    summary1 = paper1_results.get("summary", "")
                    summary2 = paper2_results.get("summary", "")
                    
                    # 创建综合的节点处理器
                    from agent.nodes import PaperPalNodes
                    nodes = PaperPalNodes(st.session_state.agent.api_key)
                    
                    # 创建综合状态
                    combined_state = {
                        "summary": f"论文A: {summary1}\n\n论文B: {summary2}",
                        "cleaned_text": f"{summary1} {summary2}"
                    }
                    
                    # 执行推荐分析
                    combined_state = nodes.recommendation_analysis_node(combined_state)
                    
                    # 执行推荐生成
                    if combined_state.get("recommendation_analysis_complete", False):
                        combined_state = nodes.recommendation_generation_node(combined_state)
                        
                        recommendations = combined_state.get("recommendations", "推荐生成失败")
                        
                        st.markdown("#### 基于两篇论文的综合推荐")
                        st.markdown(recommendations)
                    else:
                        st.warning("推荐分析失败，无法生成综合推荐")
                        
                except Exception as e:
                    st.error(f"生成综合推荐时出错: {str(e)}")
        
        st.divider()

        # 显示原始推荐结果
        st.markdown("#### 原始推荐结果")
                
        st.markdown(f"##### 📄 {results['paper1_title']}")
        rec1 = paper1_results.get("recommendations", "推荐生成失败")
        st.markdown(rec1)

        st.divider()
        
        st.markdown(f"##### 📄 {results['paper2_title']}")
        rec2 = paper2_results.get("recommendations", "推荐生成失败")
        st.markdown(rec2)

    with tab7:  # 专家视角部分
        st.markdown("### 📝 专家视角")

        st.markdown(f"##### 📄 {results['paper1_title']}")
        expert_feedback1 = paper1_results.get("expert_feedback", "专家评价生成失败")
        st.markdown(expert_feedback1)

        st.divider()

        st.markdown(f"##### 📄 {results['paper2_title']}")
        expert_feedback2 = paper2_results.get("expert_feedback", "专家评价生成失败")
        st.markdown(expert_feedback2)

    with tab8:
        st.markdown("### 🔍 论文溯源分析")

        if paper1_results.get("trace_complete", False):
            citation_analysis1 = paper1_results.get("citation_analysis", "溯源分析失败")
            citation_graph1 = paper1_results.get("citation_graph", "")

            st.markdown("#### 📊 引用影响力分析")
            st.markdown(citation_analysis1)

            if citation_graph1:
                try:
                    timestamp = int(time.time() * 1000)
                    render_mermaid_with_html(citation_graph1, f"citation_{timestamp}")
                except Exception as e:
                    st.code(citation_graph1, language="mermaid")
            else:
                st.info("未生成引用关系图")
        else:
            st.info("溯源分析结果暂未生成")

        st.divider()

        if paper2_results.get("trace_complete", False):
            citation_analysis2 = paper2_results.get("citation_analysis", "溯源分析失败")
            citation_graph2 = paper2_results.get("citation_graph", "")

            st.markdown("#### 📊 引用影响力分析")
            st.markdown(citation_analysis2)

            if citation_graph2:
                try:
                    timestamp = int(time.time() * 1000)
                    render_mermaid_with_html(citation_graph2, f"citation_{timestamp}")
                except Exception as e:
                    st.code(citation_graph2, language="mermaid")
            else:
                st.info("未生成引用关系图")
        else:
            st.info("溯源分析结果暂未生成")
            
    with tab9:
        st.markdown("### 📈 处理报告对比")
        col1, col2 = st.columns(2)
        
        with col1:
            st.markdown(f"#### 📄 {results['paper1_title']}")
            paper_info1 = st.session_state.agent.get_paper_info(paper1_results)
            for key, value in paper_info1.items():
                st.metric(key, value)
            
            st.markdown("#### ⚙️ 处理状态")
            status1 = st.session_state.agent.get_processing_status(paper1_results)
            for component, completed in status1.items():
                status_icon = "✅" if completed else "❌"
                st.markdown(f"{status_icon} **{component}**: {'完成' if completed else '失败'}")

            processing_report1 = paper1_results.get("processing_report", "")
            if processing_report1:
                st.markdown(processing_report1)
        
        with col2:
            st.markdown(f"#### 📄 {results['paper2_title']}")
            paper_info2 = st.session_state.agent.get_paper_info(paper2_results)
            for key, value in paper_info2.items():
                st.metric(key, value)
            
            st.markdown("#### ⚙️ 处理状态")
            status2 = st.session_state.agent.get_processing_status(paper2_results)
            for component, completed in status2.items():
                status_icon = "✅" if completed else "❌"
                st.markdown(f"{status_icon} **{component}**: {'完成' if completed else '失败'}")

            processing_report2 = paper2_results.get("processing_report", "")
            if processing_report2:
                st.markdown(processing_report2)

def main():
    """主函数"""
    # 初始化
    init_session_state()
    
    # 渲染界面
    render_sidebar()
    render_main_content()

    # 渲染对比结果
    if st.session_state.comparison_mode and st.session_state.comparison_results:
        render_comparison_results()
    else:
        render_results()
    
    # 页脚
    st.divider()
    st.markdown("""
    <div style='text-align: center; color: gray;'>
        <p>🤖 PaperPal - 基于GLM-4-Flash的论文速读Agent | 
        <a href='https://gitee.com/winnnieee/paper-pal/' target='_blank'>Gitee</a> | 
        Made with ❤️ and Streamlit</p>
    </div>
    """, unsafe_allow_html=True)

if __name__ == "__main__":
    try:
        # 验证配置
        Config.validate_config()
        main()
    except Exception as e:
        st.error(f"启动失败: {str(e)}")
        st.info("请检查配置文件和API Key设置")